unit uCouchForm;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TreeView, FMX.Layouts,
  chimera.couch, chimera.json, FMX.Memo;

type
  TfrmMain = class(TForm)
    tvDB: TTreeView;
    txtDoc: TMemo;
    Splitter1: TSplitter;
    procedure FormCreate(Sender: TObject);
    procedure tvDBChange(Sender: TObject);
  private
    couch : TCouchDB;
  public
    procedure DoServerClick(Sender : TObject);
    procedure DoDatabaseClick(Sender : TObject);
    procedure DoDocumentClick(Sender : TObject);
  end;

var
  frmMain: TfrmMain;

implementation

uses uLoginForm;

{$R *.fmx}

procedure TfrmMain.DoDatabaseClick(Sender: TObject);
var
  ti : TTreeViewItem;
begin
  ti := TTreeViewItem(Sender);
  txtDoc.Text := FormatJSON(couch[ti.Text].Info.AsJSON);
end;

procedure TfrmMain.DoDocumentClick(Sender: TObject);
var
  ti : TTreeViewItem;
begin
  ti := TTreeViewItem(Sender);
  txtDoc.Text := FormatJSON(couch[ti.ParentItem.Text][ti.Text].Get.AsJSON);
end;

procedure TfrmMain.DoServerClick(Sender: TObject);
begin
  txtDoc.Text := FormatJSON(couch.stats.AsJSON);
end;

procedure TfrmMain.FormCreate(Sender: TObject);
var
  ti : TTreeViewItem;
  frm : TfrmLogin;
begin
  couch := TCouchDB.Create;
  frm := TfrmLogin.Create(nil);
  try
    if frm.ShowModal = mrCancel then
    begin
      Application.Terminate;
      exit;
    end;
    ti := TTreeViewItem.Create(tvDB);
    ti.Text := frm.edtServer.Text;
    ti.Parent := tvDB;
    ti.OnClick := DoServerClick;

    couch.URL := frm.edtServer.Text;

    if (frm.edtUsername.Text <> '') and (frm.edtPassword.Text <> '') then
      couch.Session.Login(frm.edtUsername.Text,frm.edtPassword.Text);
  finally
    frm.Free;
  end;


  couch.EachDatabase(procedure(db : string)
  begin
    ti := TTreeViewItem.Create(tvDB);
    ti.Parent := tvDB.Items[0];
    ti.Text := db;
    ti.OnClick := DoDatabaseClick;
    couch[db].AllDocuments.Arrays['rows'].Each(procedure(obj : IJSONObject)
    var
      tiChild : TTreeViewItem;
    begin
      tiChild := TTreeViewItem.Create(tvDB);
      tiChild.Parent := ti;
      tiChild.Text := obj.Strings['id'];
      tiCHild.OnClick := DoDocumentClick;
    end);
  end);
end;

procedure TfrmMain.tvDBChange(Sender: TObject);
begin
  if tvDB.Selected <> nil then
  begin
    case tvDB.Selected.Level of
      1: DoServerClick(tvDB.Selected);
      2: DoDatabaseClick(tvDB.Selected);
      3: DoDocumentClick(tvDB.Selected);
    end;
  end;
end;

end.
